﻿using AdminSystem.Application.Commands.BreedCommands;
using AdminSystem.Domain.Entities;
using AdminSystem.EntityFramworkCore;
using AdminSystem.Repositories.Interfaces;
using AutoMapper;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace AdminSystem.Application.CommandHandlers.BreedCommandHandlers
{
    public class BreedAddCommandHandler : IRequestHandler<BreedAddCommand, APIResult<object>>
    {
        private readonly IBaseRepositories<Traceability> traceabilityBase;
        private readonly IBaseRepositories<Breed> breedBase;
        private readonly IMapper mapper;
        public BreedAddCommandHandler(IBaseRepositories<Traceability> traceabilityBase, IBaseRepositories<Breed> breedBase, IMapper mapper)
        {
            this.traceabilityBase = traceabilityBase;
            this.breedBase = breedBase;
            this.mapper = mapper;
        }
        public async Task<APIResult<object>> Handle(BreedAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Message = "添加成功";
            result.Codes = APIState.Success;
            using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    Breed breed = mapper.Map<Breed>(request);
                    breed.CreateTime = DateTime.Now;
                    await breedBase.Add(breed);

                    var data = await traceabilityBase.GetById(request.Id);
                    data.BreedId = breed.BreedId;
                    await traceabilityBase.Update(data);

                    scope.Complete();
                }
                catch (Exception exp)
                {

                    result.Message = "添加失败" + " " + exp.Message;
                    result.Codes = APIState.BadRequest;
                }
            }
           
            return await Task.FromResult(result);
        }
    }
}
